<template>
  <div class="img-container">
    <img :src="src" alt="" class="show-img" v-if="show" />
    <i class="el-icon-plus icon-add" v-else></i>
    <input type="file" @change="changeimg" class="select-img" ref="file" name="file" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      src: ''
    }
  },
  methods: {
    changeimg(e) {
      if (!/image\/\w+/.test(e.target.files[0].type)) {
        return alert('只能选择图片')
      }
      const reader = new FileReader()
      reader.readAsDataURL(e.target.files[0])
      reader.addEventListener('load', () => {
        this.src = reader.result
        this.show = true
      })

      this.$emit('change-img', this.$refs.file.files[0])
    }
  },
  watch: {}
}
</script>

<style lang="less" scope>
.img-container {
  position: relative;
  width: 150px;
  height: 150px;
  border: 1px dotted skyblue;
  border-radius: 15px;
  overflow: hidden;
  .show-img {
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
    // max-width: 100%;
  }
  .select-img {
    width: 100%;
    height: 100%;
    opacity: 0;
  }
  .icon-add {
    position: absolute;
    color: gray;
    font-size: 50px;
    margin: 50px;
  }
}
</style>
